package com.example.xgsweather.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.RemoteViews;

import com.example.xgsweather.R;
import com.example.xgsweather.activity.MainActivity;
import com.example.xgsweather.util.HttpUtil;
import com.example.xgsweather.util.LogUtil;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherWidget extends AppWidgetProvider {

    private static final String TAG = "WeatherWidget测试";
    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        String action = intent.getAction();
        if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) {
            onUpdate(context, AppWidgetManager.getInstance(context),
                    AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, WeatherWidget.class)));
        }
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        mContext = context.getApplicationContext();
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    private void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_weather);
        // 创建一个 Intent 对象，指向应用程序的启动活动
        Intent launchIntent = new Intent(context, MainActivity.class);
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launchIntent, PendingIntent.FLAG_MUTABLE);
        views.setOnClickPendingIntent(R.id.fl_widget_weather, pendingIntent);
        // Update the views with the weather data
        new WeatherTask(views, appWidgetManager, appWidgetId).execute();
    }

    private class WeatherTask extends AsyncTask<Void, Void, WeatherData> {

        private RemoteViews views;
        private AppWidgetManager appWidgetManager;
        private int appWidgetId;

        WeatherTask(RemoteViews views, AppWidgetManager appWidgetManager, int appWidgetId) {
            this.views = views;
            this.appWidgetManager = appWidgetManager;
            this.appWidgetId = appWidgetId;
        }

        @Override
        protected WeatherData doInBackground(Void... params) {
            WeatherData mWeatherData = null;
            String mCityName = "";
            String temperature = "";
            String description = "";
            while (mCityName.equals("") || temperature.equals("") || description.equals("")) {
                LogUtil.d("doInBackground while");
                SharedPreferences prefs = mContext.getSharedPreferences("current_city", Context.MODE_PRIVATE);
                mCityName = prefs.getString("county_name", "");
                temperature = prefs.getString("temperature", "");
                description = prefs.getString("description", "");
                mWeatherData = new WeatherData(mCityName);
                mWeatherData.setTemperature(temperature);
                mWeatherData.setDescription(description);
            }
            return mWeatherData;
        }

        @Override
        protected void onPostExecute(WeatherData weather) {
            HttpUtil.sendOkHttpRequest(HttpUtil.requestBingPic, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    LogUtil.e(e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = response.body().byteStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    views.setImageViewBitmap(R.id.widget_weather_icon, bitmap);
                    views.setTextViewText(R.id.widget_location, weather.getLocation());
                    views.setTextViewText(R.id.widget_temperature, String.valueOf(weather.getTemperature()));
                    views.setTextViewText(R.id.widget_description, weather.getDescription());
                    //appWidgetManager.updateAppWidget(appWidgetId, views);
                }
            });
        }
    }

    private static class WeatherData {
        private String location;
        private String temperature;
        private String description;
        private int iconId = R.drawable.logo;

        public WeatherData(String location) {
            this.location = location;
        }

        public WeatherData(String location, String temperature, String description, int iconId) {
            this.location = location;
            this.temperature = temperature;
            this.description = description;
            this.iconId = iconId;
        }

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }

        public String getTemperature() {
            return temperature;
        }

        public void setTemperature(String temperature) {
            this.temperature = temperature;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public int getIconId() {
            return iconId;
        }

        public void setIconId(int iconId) {
            this.iconId = iconId;
        }
    }

}